package com.siqi.hr.system.organization.controller;

import com.siqi.hr.common.Constants;
import com.siqi.hr.common.utils.Const;
import com.siqi.hr.common.utils.TableConstant;
import com.siqi.hr.system.common.enums.FieldEditPageEnum;
import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.common.model.ModuleType;
import com.siqi.hr.system.common.model.filter.QueryDataEntity;
import com.siqi.hr.system.common.service.CommonOperationService;
import com.siqi.hr.system.common.utils.Common;
import com.siqi.hr.system.common.utils.QueryDataUtil;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.entity.FieldRecord;
import com.siqi.hr.system.custom.entity.Query;
import com.siqi.hr.system.custom.service.EntityOperationService;
import com.siqi.hr.system.custom.service.EntityRecordService;
import com.siqi.hr.system.custom.service.FieldEmployeeService;
import com.siqi.hr.system.custom.service.QueryService;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.entity.RoleEntityScope;
import com.siqi.hr.system.organization.service.RoleService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 角色信息维护控制器
 * @author     xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Controller
@RequestMapping("Role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private FieldEmployeeService fieldEmployeeService;
    @Autowired
    private CommonOperationService commonOperationService;
    @Autowired
    private EntityOperationService entityOperationService;
    @Autowired
    private EntityRecordService entityRecordService;

    /**
     * 初始化角色列表页面
     * @author         xiaogq
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "initRole", method = RequestMethod.GET)
    public ModelAndView initRole(HttpServletRequest request, HttpSession session) throws Exception{
        ModelAndView mav = new ModelAndView();
        Employee emp = (Employee) session.getAttribute("emp");
        //获取头部列表操作按钮
        List<EntityOperation> listButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), TableConstant.ROLE_TCODE, OperationEnum.showList);
        //获取角色头部
        Map<String,Object> columnMap = fieldEmployeeService.getEntityColumns(emp,TableConstant.ROLE_TCODE, true,true);
        mav.addObject("listButtons",listButtons);
        mav.addObject("columns",columnMap.get("columns"));
        mav.addObject("fields", columnMap.get("fields"));
        mav.addObject("entity", new EntityRecord(TableConstant.ROLE_TCODE,"角色"));
        mav.setViewName("system/organization/role/role_list");
        return mav;
    }

    /**
     * 获取角色列表数据
     * @author         xiaogq
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "queryRoleAll")
    @ResponseBody
    public Map<String,Object> queryDept(HttpSession session, HttpServletRequest request) throws Exception{
        //获取搜索条件、当前登录用户、部门以及分页数据信息
        QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
        //设置列表数据分页查询
        queryData.setUsepager(true);
        queryData.setBootstrapQuery(true);
        //获取列头操作按钮
        List<EntityOperation> colButtons = entityOperationService.queryEntityOperationByHere(queryData.getEmployee().getRole(), TableConstant.ROLE_TCODE, OperationEnum.showColumn);
        Map<String, Object> resultMap =  commonOperationService.queryCustomObjectAll(queryData);
        //处理可登录模块字段
        List<Map<String, Object>> datasResult = (List<Map<String, Object>>) resultMap.get(Const.ROWS);
        for(Map<String, Object> map : datasResult){
            List<EntityOperation> operationList = new ArrayList<EntityOperation>();
            for(EntityOperation operation : colButtons){
                operationList.add(operation);
            }
            String loginModule = map.get("loginModule_varchar") == null ? "" : map.get("loginModule_varchar").toString();
            String roleId = map.get("id") == null ? "" : map.get("id").toString();
            map.put("loginModule_varchar", Common.tranformLoginModule(loginModule));
            //处理列前操作如果是管理员、人资、普通员工角色则没有删除按钮
            if(roleId.equals(Constants.ROOTROLEID)){
                EntityOperation operation = new EntityOperation("删除","fun_delete","","glyphicon glyphicon-trash",OperationEnum.showColumn.name(),new EntityRecord(TableConstant.ROLE_TCODE));
                operationList.remove(operation);
            }
            //添加列表列前操作按钮
            map.put("operation", operationList);
        }
        return resultMap;
    }

    /**
     * 添加角色初始化
     * @author         xiaoxm
     * @return
     */
    @RequestMapping(value = "roleAddInit", method = RequestMethod.GET)
    public ModelAndView roleAddInit(HttpServletRequest request) throws Exception{
        EntityRecord entity = new EntityRecord(TableConstant.ROLE_TCODE,"角色");
        ModelAndView andView = new ModelAndView();
        andView.addObject("entity", entity);
        andView.addObject("modList", ModuleType.getAllModule());
        andView.addObject("saveUrl", "Role/roleSave.do");
        andView.setViewName("system/organization/role/role_add");
        return andView;
    }

    /**
     * 添加角色保存方法
     * @author         xiaoxm
     * @author
     * @Return ModelAndView
     */
    @RequestMapping(value="roleSave", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject roleSave(HttpServletRequest request) throws Exception{
        JSONObject balkJson = new JSONObject();
        balkJson.put("flag",false);
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = entityRecordService.queryEntityRecordById(TableConstant.ROLE_TCODE);
        //获取前端传过来的form表单值
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey().toString();
            String[] value = entry.getValue();
            if(!key.equals("entityId")) {
                if (key.equals("module")){
                    continue;
                }
                dataMap.put(key,value[0]);
            }
        }
        String roleId = roleService.addRoleData(dataMap, entity, emp);
        if(StringUtils.isNotBlank(roleId)){
            balkJson.put("flag",true);
        }
        return balkJson;
    }

    /**
     * 修改角色页面初始化
     * @author         xiaoxm
     * @return
     */
    @RequestMapping(value = "roleEditInit", method = RequestMethod.GET)
    public ModelAndView roleEditInit(String id, HttpServletRequest request) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = new EntityRecord(TableConstant.ROLE_TCODE,"角色");
        //根据实体id、角色id获取添加，编辑页显示字段
        List<FieldRecord> fields = commonOperationService.getEditOrViewPageFields(TableConstant.ROLE_TCODE, emp.getRole().getId(),FieldEditPageEnum.hidden_edit);
        //根据id获取该记录id
        Map<String, Object> dataMap = commonOperationService.queryTDataInfoById(TableConstant.ROLE_TCODE,id,fields);
        ModelAndView andView = new ModelAndView();
        andView.addObject("entity", entity);
        andView.addObject("dataMap", dataMap);
        andView.addObject("saveUrl", "Role/roleEdit.do");
        andView.setViewName("system/organization/role/role_edit");
        return andView;
    }

    /**
     * 修改角色保存方法
     * @author         xiaoxm
     * @Return ModelAndView
     */
    @RequestMapping(value="roleEdit", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject roleEdit(HttpServletRequest request, String id) throws Exception{
        JSONObject balkJson = new JSONObject();
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = entityRecordService.queryEntityRecordById(TableConstant.ROLE_TCODE);
        //获取前端传过来的form表单值
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey().toString();
            String[] value = entry.getValue();
            if(!key.equals("entityId") && !key.equals("id")){
                dataMap.put(key,value[0]);
            }
        }
        int counts = roleService.updateRoleData(dataMap, entity, emp, id);
        balkJson.put("flag",counts > 0);
        return balkJson;
    }

    /**
     * 删除角色数据
     * @author         xiaoxm
     * @param id
     * @throws Exception
     *
     */
    @RequestMapping(value = "roleDelete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject roleDelete(String id) throws Exception{
        JSONObject balkJson = roleService.deleteRole(TableConstant.ROLE_TNAME, id);
        return balkJson;
    }

    /**
     * 角色查看页面
     * @author         xiaoxm
     * @return
     */
    @RequestMapping(value = "roleView", method = RequestMethod.GET)
    public ModelAndView roleView(String id, HttpServletRequest request) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        //得到当前查看记录的名称
        String rowName = request.getParameter("rowName");
        List<EntityOperation> listButtons = new ArrayList<EntityOperation>();
        //获取详情页操作按钮
        List<EntityOperation> viewButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), TableConstant.ROLE_TCODE, OperationEnum.showView);
        for(EntityOperation operation : viewButtons){
            if(operation.getIcon().endsWith("-edit")){
                operation.setIcon("image/common/operation/oper_UPDATE.png");
            }else if(operation.getIcon().endsWith("-trash")){
                if(id.equals(Constants.ROOTROLEID)){
                    continue;
                }else{
                    operation.setIcon("image/common/operation/oper_DELETE.png");
                }
            }
            listButtons.add(operation);
        }
        //获取详情页字段信息
        Map<String, Object> resultDataMap = commonOperationService.getViewPageFields(id,TableConstant.ROLE_TCODE, emp.getRole().getId(), FieldEditPageEnum.hidden_show);
        //获取字段值
        Map<String,Object> dataMap = (Map<String, Object>) resultDataMap.get("datas");
        Map<String,Object> columnMap = fieldEmployeeService.getEntityColumns(emp,TableConstant.EMPLOYEE_TCODE, true,false);
        //处理可登录模块
        String loginModule = dataMap.get("loginModule_varchar") == null ? "" : dataMap.get("loginModule_varchar").toString();
        dataMap.put("loginModule_varchar", Common.tranformLoginModule(loginModule));
        ModelAndView andView = new ModelAndView();
        andView.addObject("id",id);
        andView.addObject("rowName",rowName);
        andView.addObject("entity", new EntityRecord(TableConstant.ROLE_TCODE,"角色"));
        andView.addObject("listButtons", listButtons);
        andView.addObject("dataMap", dataMap);
        andView.addObject("columns",columnMap.get("columns"));
        andView.addObject("fields", columnMap.get("fields"));
        andView.setViewName("system/organization/role/role_view");
        return andView;
    }

    /**
     * 角色数据停用
     * @author         xiaoxm
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "roleDisable")
    @ResponseBody
    public String employeeDisable(String id) throws Exception {
        roleService.disableRole(TableConstant.ROLE_TNAME, id);
        JSONObject balkJson = new JSONObject();
        balkJson.put("success","success");
        return balkJson.toString();
    }

    /**
     * 角色数据启用
     * @author         xiaoxm
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "roleEnable")
    @ResponseBody
    public String employeeEnable(String id) throws Exception {
        roleService.enableRole(TableConstant.ROLE_TNAME, id);
        JSONObject balkJson = new JSONObject();
        balkJson.put("success","success");
        return balkJson.toString();
    }

    /**
     * 设置角色系统权限页面
     * @author         xiaogq
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("queryRoleMenuPms")
    public ModelAndView queryRoleMenuPms(HttpServletRequest request, HttpSession session) throws Exception {
        String roleid = request.getParameter("roleid");
        String kind = request.getParameter("kind");
        String menus = roleService.queryRoleMenus(roleid, kind);

        ModelAndView mav = new ModelAndView();
        mav.addObject("roleid", roleid);
        mav.addObject("isAdmin", roleid.equals(Constants.ROOTROLEID));
        mav.addObject("kind", kind);
        mav.addObject("menus", menus);
        mav.setViewName("system/organization/role/role_menu");
        return mav;
    }

    /**
     * 角色系统配置权限、crm权限保存
     * @author         xiaogq
     * @param request
     * @param session
     * @throws Exception
     */
    @RequestMapping("updateRolePms")
    @ResponseBody
    public JSONObject updateRolePms(HttpServletRequest request, HttpSession session) throws Exception {
        String roleid = request.getParameter("roleid");
        String kind = request.getParameter("kind");
        String menuids = request.getParameter("menuids");
        JSONObject obj = roleService.updateRolePms(roleid, kind, menuids);
        return  obj;
    }

    /**
     * 初始化角色操作权限
     * @author         xiaogq
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("queryRoleOperationPms")
    public ModelAndView queryRoleOperationPms(HttpServletRequest request, HttpSession session) throws Exception {
        String roleid = request.getParameter("roleid");
        //根据角色id获取操作权限列表受权限控制实体信息
        List<Map<String, Object>> operPmsList = roleService.queryRoleOperationPms(roleid);

        ModelAndView mav = new ModelAndView();
        mav.addObject("roleid", roleid);
        mav.addObject("isAdmin", roleid.equals(Constants.ROOTROLEID));
        mav.addObject("operPmsList", operPmsList);
        mav.setViewName("system/organization/role/role_operation");
        return mav;
    }

    /**
     * 保存系统操作权限配置信息方法
     * @author         xiaogq
     * @param request
     * @param session
     * @throws Exception
     */
    @RequestMapping(value = "updateRoleOperationPms", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateRoleOperationPms(HttpServletRequest request, HttpSession session) throws Exception {
        String roleid = request.getParameter("roleid");
        String reodata = request.getParameter("reodata");

        List<Map<String, Object>> reoList = new ArrayList<Map<String, Object>>();
        String[] reoArr = reodata.substring(0, reodata.lastIndexOf("&")).split("&");
        for (int i = 0; i < reoArr.length; i++) {
            String[] reoval = reoArr[i].split("=");
            String [] allOpts = reoval[1].split(";");
            for(int j = 0; j < allOpts.length; j++){
                String [] opts = allOpts[j].split("_");
                String operId = opts[0];
                String operFlag = opts[1];
                //如果是停用/启用操作
                if(operId.contains("/")){
                    String [] opIds = operId.split("/");
                    for(int n = 0; n < opIds.length; n++){
                        Map<String, Object> enablemap = new HashMap<String, Object>();
                        enablemap.put("entityId", reoval[0]);
                        enablemap.put("operId", opIds[n]);
                        enablemap.put("operFlag", operFlag);
                        reoList.add(enablemap);
                    }
                }else{
                    Map<String, Object> reoMap = new HashMap<String, Object>();
                    reoMap.put("entityId", reoval[0]);
                    reoMap.put("operId", operId);
                    reoMap.put("operFlag", operFlag);
                    reoList.add(reoMap);
                }
            }
        }
        JSONObject obj = roleService.updateRoleOperationPms(roleid, reoList);
        return obj;
    }

    /**
     * 初始化角色数据权限页面
     * @author         xiaogq
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("queryRoleDataPms")
    public ModelAndView queryRoleDataPms(HttpServletRequest request, HttpSession session) throws Exception {
        String roleid = request.getParameter("roleid");
        //根据角色id获取数据权限列表受权限控制实体信息
        List<RoleEntityScope> dataPmsList = roleService.queryRoleDataPms(roleid);
        //获取数据权限所有枚举值(全部，本部门及下级部门，本部门，相关部门，自己，无)
        List<Map<String, Object>> dataScopeList = roleService.queryAllDataScope();

        ModelAndView mav = new ModelAndView();
        mav.addObject("roleid", roleid);
        mav.addObject("isAdmin", roleid.equals(Constants.ROOTROLEID));
        mav.addObject("dataPmsList", dataPmsList);
        mav.addObject("dataScopeList", dataScopeList);
        mav.setViewName("system/organization/role/role_data");
        return mav;
    }

    /**
     * 保存系统数据权限配置信息方法
     * @author         xiaogq
     * @param request
     * @param session
     * @throws Exception
     */
    @RequestMapping("updateRoleDataPms")
    @ResponseBody
    public JSONObject updateRoleDataPms(HttpServletRequest request, HttpSession session) throws Exception {
        //获得角色id
        String roleid = request.getParameter("roleid");
        //获得角色对应实体权限数据范围
        String reddata = request.getParameter("reddata");
        List<Map<String, Object>> redList = new ArrayList<Map<String, Object>>();
        String[] redArr = reddata.split("&");
        for (int i = 0; i < redArr.length; i++) {
            Map<String, Object> resdMap = new HashMap<String, Object>();
            String[] redval = redArr[i].split("=");
            resdMap.put("entityId", redval[0]);
            resdMap.put("viewLevel", redval[1].split("-")[0]);
            resdMap.put("editLevel", redval[1].split("-")[1]);
            resdMap.put("deleteLevel", redval[1].split("-")[2]);
            redList.add(resdMap);
        }
        JSONObject obj = roleService.updateRoleDataPms(roleid, redList);
        return obj;
    }

}
